package operate;

import java.io.File;

import storage.Field;
import storage.Table;
import java.util.List;

import entry.DBMS;
import entry.OperUtil;

public class Create implements Operate {
	private Table table = null;
	private String account = null;
	private String name = null;
	private String fieldName = null;

	public Create(String account) {
		this.account = account;
	}

	@Override
	public void start() throws Exception {
		switch (ParseCmd.parseCreate(this)) {
		case 1:
			parseCreateDatabase();
			break;
		case 2:
			parseCreateTable();
			break;
		default:
			System.out.println("Error");
			break;
		}
	}

	private void parseCreateDatabase() throws Exception {
		createDatabase();
	}

	private void parseCreateTable() throws Exception {
		this.table = ParseCmd.parseTable(this.account, this.name);
		this.createTable();
		OperUtil.perpetuateTable(this.table, this.table.getConfigFile());
		OperUtil.perpetuateDatabase(DBMS.dataDictionary, DBMS.dataDictionary.getConfigFile());
	}

	private void createDatabase() {
		File dir = new File(DBMS.ROOTPATH + File.separator + this.name);
		if (dir.exists()) {
			throw new RuntimeException("数据库已创建");
		}
		System.out.println(dir.getPath());
		dir.mkdirs();
	}

	
	private void createTable() throws Exception {
		this.table.getFile().createNewFile();
		
		DBMS.dataDictionary.getTables().add(this.table.getTableName());
		DBMS.loadedTables.put(this.table.getTableName(), this.table);
		System.out.println("表已创建");
	}

	public Table getTable() {
		return table;
	}

	public void setTable(Table table) {
		this.table = table;
	}

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getFieldName() {
		return fieldName;
	}

	public void setFieldName(String fieldName) {
		this.fieldName = fieldName;
	}

}
